# -*- coding: utf-8 -*-
'''
@File  : sshForLinux.py
@Author: canx
@Date  : 2018/8/10 17:05
@Desc  : linux ssh 连接
'''

import paramiko
import os
import sys
import imp

def ssh2_cmd(ip,username,passwd,cmd):
    try:
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(ip,22,username,passwd,timeout=5)
        for m in cmd:
            stdin, stdout, stderr = ssh.exec_command(m)
#           stdin.write("Y")   #简单交互，输入 ‘Y’
            out = stdout.readlines()
            #屏幕输出
            for o in out:
                print(o)
        print('%s\tOK\n'%(ip))
        ssh.close()
    except :
        print('%s\tError\n'%(ip))



def sftp_upload(ip, username, password, local, remote):
    port = 22
    sf = paramiko.Transport((ip, port))
    sf.connect(username = username,password = password)
    sftp = paramiko.SFTPClient.from_transport(sf)
    try:
        if os.path.isdir(local):#判断本地参数是目录还是文件
            for f in os.listdir(local):#遍历本地目录
                sftp.put(os.path.join(local+f),os.path.join(remote+f))#上传目录中的文件
        else:
            sftp.put(local,remote)#上传文件
    except Exception as e:
        print('upload exception:',e)
    sf.close()



if __name__=='__main__':
    # cmd = ['/home/app/software/jdk1.8.0_91/bin/java -jar /home/app/bhge/bhge-0.0.1-SNAPSHOT.jar /dev/null  &', 'echo done!']#你要执行的命令列表
    cmd = ['source /home/app/.bash_profile && sh /home/app/bhge/start.sh',
           'echo done!']  # 你要执行的命令列表
    ip = "47.98.156.138"
    username = "app"  #用户名
    passwd = "Techm#002"    #密码
    local = "F:\\softCode\\ge-code\\bhge\\target\\bhge-0.0.1-SNAPSHOT.jar"
    remote = "/home/app/bhge/bhge-0.0.1-SNAPSHOT.jar"
    print("Begin......")
    ssh2_cmd(ip, username, passwd, cmd)
    # sftp_upload(ip, username, passwd, local, remote)



